package com.ruoyi.subject.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CreateId;
import com.ruoyi.common.utils.pdf.CreatePdfUtil;
import com.ruoyi.ky450.domain.TargetBaseInfo;
import com.ruoyi.ky450.service.ITargetBaseInfoService;
import com.ruoyi.network.domain.TargetEvent;
import com.ruoyi.network.domain.TargetPeople;
import com.ruoyi.network.service.INetworkDealService;
import com.ruoyi.subject.domain.*;
import com.ruoyi.common.enums.SubType;
import com.ruoyi.subject.mapper.*;
import com.ruoyi.subject.service.ISpecialSubjectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 11975
 */
@Slf4j
@Service
public class SpecialSubjectServiceImpl implements ISpecialSubjectService {

    @Autowired
    SubjectCatalogMapper catalogMapper;
    @Autowired
    SubjectChapterMapper chapterMapper;
    @Autowired
    SubjectResultMapper resultMapper;
    @Autowired
    SubjectTargetMapper targetMapper;
    @Autowired
    SubjectTemplateMapper templateMapper;
    @Autowired
    TemplateChapterMapper templateChapterMapper;
    @Autowired
    ITargetBaseInfoService targetBaseInfoService;
//    @Autowired
//    INetworkDealService networkDealService;

    // TODO 命名是虚假的等后续有接口完善
    @Value("${sub.oneUrl}")
    private String oneUrl;

    @Value("${sub.twoUrl}")
    private String twourl;

    @Value("${sub.threeUrl}")
    private String threeUrl;

    @Value("${sub.fourUrl}")
    private String fourUrl;

    @Value("${sub.fiveUrl}")
    private String fiveUrl;

    @Value("${sub.sixUrl}")
    private String sixUrl;

    @Override
    public List<SubjectCatalog> getSubjectList(SubjectCatalog catalog) {

        return catalogMapper.selectList(buildSubjectCatalogQueryWrapper(catalog));
    }


    @Override
    public SubjectChapterAndTarget getSubjectChapterList(SubjectCatalog catalog) {
        List<SubjectTarget> subjectTargets = targetMapper.selectList(new QueryWrapper<SubjectTarget>()
                .eq("subject_id", catalog.getSubjectId()));
        Set<Integer> targetType = subjectTargets.stream().map(SubjectTarget::getTargetType).collect(Collectors.toSet());
        HashMap<Integer, List<Integer>> integerListHashMap = new HashMap<>();

        for (Integer integer : targetType) {
            integerListHashMap.put(integer, targetMapper.selectTargetId(catalog.getSubjectId(), String.valueOf(integer)));
        }

        List<SubjectChapter> collect = targetType.stream().map(this::selectSubjectCatalogList).flatMap(List::stream)
                .collect(Collectors.toList());

        return new SubjectChapterAndTarget(collect, integerListHashMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSubjectTemplate(SubjectTemplate template) {
        template.setTemplateId(CreateId.generateId());
        //处理json传章节名称
        template.setTemplateInfo(this.createTemplateInfo(template.getTemplateChapters()));
        String subjectType = template.getSubjectType();
        template.setSubjectType(SubType.getByType(Integer.parseInt(subjectType)).getTypeName());
        int insert = templateMapper.insert(template);
        if (insert < 1) {
            return insert;
        }
        List<TemplateCharpter> list = template.getTemplateChapters();
        for (TemplateCharpter templateChapter : list) {
            templateChapter.setId(CreateId.generateId());
            templateChapter.setTemplateId(template.getTemplateId());
            templateChapterMapper.insert(templateChapter);
        }
        return insert;
    }

    private String createTemplateInfo(List<TemplateCharpter> templateChapters) {
        JSONObject root = new JSONObject();
        root.put("title", "");
        JSONArray valueArray = new JSONArray();
        for (TemplateCharpter templateChapter : templateChapters) {

            String charpterName = templateChapter.getCharpterName();
            JSONObject tableObject = new JSONObject();
            tableObject.put("table", charpterName);
            valueArray.add(tableObject);
        }

        root.put("value", valueArray);
        return root.toString();
    }

    @Override
    public int deleteSubjectTemplate(Long[] ids) {
        int i = templateMapper.deleteBatchIds(Arrays.asList(ids));
        if (i > 0) {
            for (Long id : ids) {
                templateChapterMapper.delete(new QueryWrapper<TemplateCharpter>()
                        .eq("template_id", id));
            }
        }
        return i;
    }

    @Override
    public SubjectTemplateAndTarget getReportBaseInfo(Long id, Long subjectId) {
        List<TemplateCharpter> templateChapterList = templateChapterMapper.selectList(new QueryWrapper<TemplateCharpter>()
                .eq("template_id", id));
        List<Map<String, Object>> list = new ArrayList<>();
        for (TemplateCharpter templateChapter : templateChapterList) {
            SubjectChapter subjectChapter = chapterMapper.selectById(templateChapter.getCharpterId());
            if (null == subjectChapter) {
                continue;
            }
            //获取URL
            subjectChapter.setChapterRestful(this.jointUrl(subjectChapter) + subjectChapter.getChapterRestful());
            Map<String, Object> map = new HashMap<>();
            map.put("chapter", subjectChapter.getChapterName());
            map.put("chapterRestful", subjectChapter.getChapterRestful());
            map.put("targetType", subjectChapter.getTargetType());
            list.add(map);
        }

        List<SubjectTarget> subjectTargets = targetMapper.selectList(new QueryWrapper<SubjectTarget>()
                .eq("subject_id", subjectId));
        Set<Integer> targetType = subjectTargets.stream().map(SubjectTarget::getTargetType).collect(Collectors.toSet());
        HashMap<Integer, List<Integer>> integerListHashMap = new HashMap<>();

        for (Integer integer : targetType) {
            integerListHashMap.put(integer, targetMapper.selectTargetId(subjectId, String.valueOf(integer)));
        }

        return new SubjectTemplateAndTarget(list, integerListHashMap);
    }

    private String jointUrl(SubjectChapter subjectChapter) {
        String path = null;
        switch (subjectChapter.getTargetType()) {
            case "1":
                path = oneUrl;
                break;
            case "2":
                path = twourl;
                break;
            case "3":
                path = threeUrl;
                break;
            case "4":
                path = fourUrl;
                break;
            case "5":
                path = fiveUrl;
                break;
            case "6":
                path = sixUrl;
                break;
            default:
                throw new IllegalArgumentException("未找到对应类型");
        }

        return path;

    }

    @Override
    public int addSubjectCatalog(SubjectCatalog catalog) {
        //默认未生成
        catalog.setResultNum(0);
        catalog.setSubjectId(CreateId.generateId());
        int insert = catalogMapper.insert(catalog);
        if (insert < 1) {
            return insert;
        }
        StringBuilder builder = new StringBuilder();
        if (CollectionUtils.isNotEmpty(catalog.getTargets())) {
            for (SubjectTarget target : catalog.getTargets()) {
                target.setSubjectId(catalog.getSubjectId());
                target.setId(CreateId.generateId());
                target.setTargetType(catalog.getSubjectType());
                targetMapper.insert(target);
                builder.append(target.getTargetName()).append(",");
            }
        }
        catalog.setSubjectKeyword(builder.toString());
        return catalogMapper.updateById(catalog);
    }

    @Override
    public int delSubjectCatalog(Long[] ids) {
        for (Long id : ids) {
            targetMapper.delete(new QueryWrapper<SubjectTarget>()
                    .eq("subject_id", id));
            resultMapper.delete(new QueryWrapper<SubjectResult>()
                    .eq("subject_id", id));
        }
        return catalogMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public List<Map<String, Object>> getTargetList(Integer type) {
// targetBaseInfo targetClass       0:雷达 1:导弹 2:飞机 3:舰船 4:火炮 5:装甲车 6:固定设施)
//        1舰船 2飞机 3雷达 4导弹 5固定设施 6人物 7事件
        Integer targetClass = null;
        Integer peoOrEve = null;
        switch (type) {
            case 1:
                targetClass = 3;
                break;
            case 2:
                targetClass = 2;
                break;
            case 3:
                targetClass = 0;
                break;
            case 4:
                targetClass = 1;
                break;
            case 5:
                targetClass = 6;
                break;
            case 6:
                //人物
                peoOrEve = 1;
                break;
            case 7:
                //事件
                peoOrEve = 2;
                break;
            default:
                throw new ServiceException("专题类型不存在：" + type);
        }
        if (targetClass != null) {
            TargetBaseInfo baseInfo = new TargetBaseInfo();
            baseInfo.setTargetClass(targetClass);
            List<TargetBaseInfo> targetBaseInfos = targetBaseInfoService.selectTargetBaseInfoList(baseInfo);
            return targetBaseInfos.stream().map(var -> {
                Map<String, Object> map = new HashMap<>(4);
                map.put("id", var.getId());
                map.put("name", var.getTargetName());
                return map;
            }).collect(Collectors.toList());
        } else if (peoOrEve == 1) {
//            List<TargetPeople> list = networkDealService.getTargetPeopleList(null);
//            return list.stream().map(var -> {
//                Map<String, Object> map = new HashMap<>(4);
//                map.put("id", var.getUserId());
//                map.put("name", var.getUserName());
//                return map;
//            }).collect(Collectors.toList());
        } else {
            List<TargetEvent> list = networkDealService.getTargetEventList(null);
            return list.stream().map(var -> {
                Map<String, Object> map = new HashMap<>(4);
                map.put("id", var.getEventId());
                map.put("name", var.getEventName());
                return map;
            }).collect(Collectors.toList());
        }
    }

    /**
     * 查询专题下关联目标
     *
     * @param subjectId  专题id
     * @param targetType 目标类型(1舰船 2飞机 3雷达 4导弹 5固定设施 6人物 7事件)
     * @return list
     */
    private List<SubjectTarget> buildSubjectTargetQueryWrapper(Long subjectId, Integer targetType) {
        return targetMapper.selectList(new QueryWrapper<SubjectTarget>()
                .eq("subject_id", subjectId)
                .eq("target_type", targetType));
    }

    /**
     * 构建subjectCatalog查询条件
     *
     * @param subjectCatalog 专题列表
     * @return queryWrapper
     */
    private QueryWrapper<SubjectCatalog> buildSubjectCatalogQueryWrapper(SubjectCatalog subjectCatalog) {
        QueryWrapper<SubjectCatalog> wrapper = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(subjectCatalog.getSubjectName())) {
            wrapper.like("subject_name", subjectCatalog.getSubjectName());
        }
        if (ObjectUtils.isNotEmpty(subjectCatalog.getSubjectKeyword())) {
            wrapper.like("subject_keyword", subjectCatalog.getSubjectKeyword());
        }
        if (ObjectUtils.isNotEmpty(subjectCatalog.getResultNum())) {
            wrapper.eq("result_num", subjectCatalog.getResultNum());
        }
        if (ObjectUtils.isNotEmpty(subjectCatalog.getTaskSource())) {
            wrapper.eq("task_source", subjectCatalog.getTaskSource());
        }
        if (ObjectUtils.isNotEmpty(subjectCatalog.getStartTime()) && ObjectUtils.isNotEmpty(subjectCatalog.getEndTime())) {
            wrapper.ge("create_time", subjectCatalog.getStartTime())
                    .le("create_time", subjectCatalog.getEndTime());
        }
        if (ObjectUtils.isNotEmpty(subjectCatalog.getSubjectType())) {
            wrapper.eq("subject_type", subjectCatalog.getSubjectType());
        }
        return wrapper;
    }


    /**
     * 根据类型查询list
     *
     * @param chapterCode 章节字典列表
     * @return list
     */
    private List<SubjectChapter> selectSubjectCatalogList(Integer chapterCode) {
        QueryWrapper<SubjectChapter> wrapper = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(chapterCode)) {
            wrapper.eq("chapter_code", chapterCode);
        }
        return chapterMapper.selectList(wrapper);
    }

    /**
     * 获取专题下所有模板
     *
     * @param type 1舰船 2飞机 3雷达 4导弹 5固定设施 6人物 7事件
     * @return
     */
    @Override
    public List<SubjectTemplate> getTempleateList(Integer type) {
        String typeName = SubType.getByType(type).getTypeName();

        QueryWrapper<SubjectTemplate> wrapper = new QueryWrapper<>();
        if (ObjectUtils.isNotEmpty(typeName)) {
            wrapper.eq("subject_type", typeName);
        }
        return templateMapper.selectList(wrapper);
    }

    /**
     * 把单个的图片合并为pdf
     *
     * @param createPdf
     * @return
     */
    @Override
    public String createPdf(CreatePdf createPdf) {

        // 获取上传路径
        String uploadPath = RuoYiConfig.getUploadPath();
        // 检查上传路径是否为空
        if (uploadPath == null || uploadPath.isEmpty()) {
            throw new IllegalArgumentException("上传路径为空，请检查配置。");
        }
        // 格式化文件名
        String fileName = formatPdfFileName(createPdf);
        File file = new File(uploadPath, fileName);
        //测试地址
//        File file = new File("D:/home/upload-ky-450/" + fileName);

        CreatePdfUtil.createPdf(file, createPdf.getPdfs());
        String targetType = SubType.getByType(Integer.parseInt(createPdf.getSubjectType())).getTypeName();

//        int insert = resultMapper.insert(new SubjectResult(createPdf.getSubjectId(), targetType, "http://192.168.3.77:1002/profile/" + fileName));
        int insert = resultMapper.insert(new SubjectResult(createPdf.getSubjectId(), targetType, file.getAbsolutePath()));

        if (0 != insert) {
            //更新专题状态创建PDF
            UpdateWrapper<SubjectCatalog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("subject_id", createPdf.getSubjectId());  // 设置更新条件

            // 创建要更新的实体对象（只需要设置需要更新的字段）
            SubjectCatalog updateEntity = new SubjectCatalog();
            updateEntity.setResultNum(1);

            // 执行更新操作
            catalogMapper.update(updateEntity, updateWrapper);
        }
//        return "http://192.168.3.77:1002/profile/" + fileName;
        return file.getAbsolutePath();
    }


    private static String formatPdfFileName(CreatePdf createPdf) {
        return String.format("%s-%s-%d.pdf",
                createPdf.getSubjectName(),
                SubType.getByType(Integer.parseInt(createPdf.getSubjectType())).getTypeName(),
                System.currentTimeMillis());
    }

    /**
     * 专题ID
     *
     * @param subjectId
     * @return
     */
    @Override
    public SubjectResult getPdfPath(Integer subjectId) {
        return resultMapper.selectOne(new QueryWrapper<SubjectResult>()
                .eq("subject_id", subjectId));
    }
}
